package com.alcohol.auth.server.service.impl;

import com.alcohol.auth.server.entity.SysUser;
import com.alcohol.auth.server.mapper.SysUserMapper;
import com.alcohol.auth.server.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 用户信息Service——实现
 * @author LiXinYu
 * @date 2025/11/7
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Resource
    private SysUserMapper sysUserMapper;

    /**
     * 根据用户名获取用户信息
     * @param username 用户名
     * @return 用户信息
     * @throws UsernameNotFoundException 无用户异常
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUser::getUsername, username);
        SysUser sysUser = sysUserMapper.selectOne(lambdaQueryWrapper);
        if (Objects.isNull(sysUser)) {
            throw new UsernameNotFoundException(username + "not found");
        }

        return User.withUsername(sysUser.getUsername()).password(sysUser.getPassword()).roles("USER").build();
    }
}
